import arrayMethods from "./array.js";
import {defineReactive} from "./defineReactive.js"
import { Dep } from "./Dep.js"
import { observe } from "./observe.js";
//将obj层级调用成响应式
export class Observer{
    constructor(val){
        //每个Observer都有dep实例
        this.dep = new Dep();

        //构造函数this是实例,把实例添加到__ob__上
        Object.defineProperty(val,'__ob__',{
            value:this,
            enumerable:false,
            writable:true,
            configurable:true
        })    

        if(Array.isArray(val)){
            Object.setPrototypeOf(val,arrayMethods)
            this.observeArray(val)
        }else{
            this.walk(val)
        }
    }
    walk(val){
        var keys = Object.keys(val);
        keys.forEach((e)=>{
            defineReactive(val,e,val[e])
        })
    }
    observeArray(val){
        // 防止数组长度变化，先缓存l
        for(let i=0,l=val.length;i<l;i++){
            observe(val[i])
        }
    }
}